<script setup>
import { ref, onMounted } from 'vue'
import defaultProduct from '../assets/logo.jpg'

const groupBuyingList = ref([])
const loading = ref(false)
const errorMessage = ref('')

// 获取拼团列表
const fetchGroupBuyList = async () => {
    try {
        loading.value = true
        errorMessage.value = ''
        
        const token = localStorage.getItem('token')
        const response = await fetch('http://localhost:3001/api/admin/groupbuy/list', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        
        const data = await response.json()
        
        if (response.ok && data.code === 200) {
            groupBuyingList.value = data.data.map(group => {
                // 检查图片URL是否有效
                let productImage = defaultProduct;
                if (group.image_url) {
                    try {
                        // 如果是JSON字符串数组，解析它并获取第一张图片
                        if (typeof group.image_url === 'string' && group.image_url.startsWith('[')) {
                            const images = JSON.parse(group.image_url);
                            if (Array.isArray(images) && images.length > 0) {
                                productImage = `http://localhost:3001${images[0]}`;
                            }
                        } else {
                            // 如果是单个URL
                            productImage = group.image_url;
                        }
                    } catch (e) {
                        console.error('处理图片URL失败:', e);
                    }
                }

                return {
                    ...group,
                    leader: {
                        name: group.creator_name,
                        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + group.creator_name
                    },
                    productImage
                };
            });
            
            // console.log('处理后的列表数据:', groupBuyingList.value);
        } else {
            errorMessage.value = data.message || '获取拼团列表失败'
        }
    } catch (error) {
        console.error('获取拼团列表失败:', error)
        errorMessage.value = '网络错误，请稍后重试'
    } finally {
        loading.value = false
    }
}

// 获取状态标签
const getStatusTag = (status) => {
    const statusMap = {
        'waiting': { text: '待开始', color: '#faad14' },
        'in_progress': { text: '进行中', color: '#52c41a' },
        'completed': { text: '已完成', color: '#1890ff' },
        'expired': { text: '已过期', color: '#ff4d4f' }
    }
    return statusMap[status] || { text: status, color: '#999' }
}

// 页面加载时获取数据
onMounted(() => {
    fetchGroupBuyList()
})
</script>

<template>
    <div class="group-buying-page">
        <div class="page-header">
            <h2>待拼团列表</h2>
            <div class="header-actions">
                <button class="refresh-btn" @click="fetchGroupBuyList" :disabled="loading">
                    <i class="fa-solid fa-rotate"></i>
                    刷新
                </button>
            </div>
        </div>

        <div v-if="loading" class="loading">
            加载中...
        </div>

        <div v-else-if="errorMessage" class="error-message">
            {{ errorMessage }}
        </div>

        <div v-else class="group-list">
            <div v-for="group in groupBuyingList" :key="group.groupbuy_id" class="group-card">
                <div class="group-header">
                    <img :src="group.leader.avatar" :alt="group.leader.name" class="leader-avatar">
                    <span class="leader-name">{{ group.leader.name }}发起的拼团</span>
                    <span class="group-status" :style="{ color: getStatusTag(group.status).color }">
                        {{ getStatusTag(group.status).text }}
                    </span>
                </div>

                <div class="group-content">
                    <div class="product-info">
                        <img 
                            :src="group.productImage" 
                            :alt="group.product_name" 
                            class="product-image"
                            @error="e => e.target.src = defaultProduct"
                        >
                        <div class="product-details">
                            <h3>{{ group.product_name }}</h3>
                            <div class="price-info">
                                <span class="group-price">¥{{ group.group_price }}</span>
                                <span class="original-price">¥{{ group.original_price }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="group-progress">
                        <div class="progress-text">
                            <span>已有{{ group.current_count }}人参团</span>
                            <span>还差{{ group.group_size - group.current_count }}人成团</span>
                        </div>
                        <div class="progress-bar">
                            <div 
                                class="progress-inner" 
                                :style="{ width: (group.current_count / group.group_size * 100) + '%' }"
                            ></div>
                        </div>
                    </div>

                    <div class="group-members">
                        <div class="member-avatars">
                            <img 
                                v-for="member in group.members" 
                                :key="member.user_id"
                                :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${member.username}`"
                                :alt="member.username"
                                class="member-avatar"
                            >
                            <div 
                                v-for="n in (group.group_size - group.members.length)" 
                                :key="'empty-' + n"
                                class="empty-avatar"
                            >
                                <i class="fa-solid fa-user-plus"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.group-buying-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--text-color);
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.3s;
}

.refresh-btn:hover {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.group-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.group-card {
  background: var(--bg-color);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
}

.group-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  gap: 12px;
}

.leader-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.leader-name {
  flex: 1;
  color: var(--text-color);
}

.group-status {
  font-size: 14px;
  font-weight: 500;
}

.group-content {
  padding: 16px;
}

.product-info {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: var(--border-radius);
}

.product-details {
  flex: 1;
}

.product-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: var(--text-color);
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.group-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.original-price {
  font-size: 14px;
  color: var(--text-color-secondary);
  text-decoration: line-through;
}

.group-progress {
  margin-bottom: 16px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: var(--text-color-secondary);
  margin-bottom: 8px;
}

.progress-bar {
  height: 4px;
  background: var(--border-color);
  border-radius: 2px;
  overflow: hidden;
}

.progress-inner {
  height: 100%;
  background: var(--primary-color);
  transition: width 0.3s ease;
}

.group-members {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.member-avatars {
  display: flex;
  gap: 8px;
}

.member-avatar,
.empty-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2px solid var(--bg-color);
}

.empty-avatar {
  background: var(--bg-color-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-color-secondary);
}

.time-left {
  font-size: 14px;
  color: #ff4d4f;
}

.group-actions {
  display: flex;
  gap: 12px;
}

.share-btn,
.join-btn {
  flex: 1;
  padding: 8px 16px;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.3s;
}

.share-btn {
  background: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-color);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.share-btn:hover {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.join-btn {
  background: var(--primary-color);
  border: none;
  color: white;
}

.join-btn:hover {
  opacity: 0.9;
}

input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s;
  outline: none;
}

input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.1);
}
</style> 